package com.qi.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.qi.common.utils.HttpUtils;
import com.qi.common.utils.R;
import com.qi.gulimall.auth.feign.MemberFeignService;
import com.qi.common.vo.MemberRespVo;
import com.qi.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 周玉琦
 * @date 2020/9/18 - 15:28
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Resource
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String,String> map = new HashMap<>();
        map.put("client_id","2398691422");
        map.put("client_secret","5667fbbca7856d69966395f8ff31e4f0");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);
        //根据code换取accessToken;
        String host = "https://api.weibo.com";
        String path = "/oauth2/access_token";
        String method = "post";
        System.out.println("host:"+host+"path:"+path+"method:"+method);
        HttpResponse response = HttpUtils.doPost(host, path, method, null, null,map);

        if(response.getStatusLine().getStatusCode()==200){
            //获取token成功
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //调用远程服务来进行登录或者注册
            R oauthlogin = memberFeignService.oauthlogin(socialUser);
            if(oauthlogin.getCode()==0){
                MemberRespVo data = oauthlogin.getData("data", new TypeReference<MemberRespVo>() {
                });
                log.info("微博登录成功,用户信息:{}",data.toString());
                session.setAttribute("loginUser",data);
                //登录成功跳回首页
                return "redirect:http://gulimall.com";
            }else{
                //登录失败,重新返回登录页
                return "redirect:http://auth.gulimall.com/login.html";
            }

        }else{
            //获取token失败返回登录页重新发送微博登录请求
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
